﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DataTables;
using DataTool;
using workflowMVC.Models;
using OneGateWF;
using Common;
using CrystalDecisions.CrystalReports.Engine;
using System.IO;
using iTextSharp.text.pdf;
using iTextSharp.text;

namespace workflowMVC.Controllers
{
    [Authorize(Roles = "Approver")]
    public class ApproveController : Controller
    {
        //
        // GET: /Approve/

        ////public ActionResult Index()
        ////{
        ////    return View();
        ////}

        public ActionResult ConfirmStu()
        {
            ViewBag.datasource = Url.Action("ConfirmStuData");
            return View("ManageTable");
        }

        public JsonResult ConfirmStuData()
        {
            var cs = Util.ValidateTaskListData(Request,x => x.Kind == 1 && x.Status == 2);
            cs.aaData.ForEach(
                x => Util.TableLinkMiscApprove(x,Url.Action("ConfirmStuDetail")));
            
            return Json(cs);
        }

        public ActionResult ConfirmStuDetail(Guid Id)
        {
            if (new wfdbEntities().TASKs.FirstOrDefault(x => x.Id == Id && x.Status ==2) == null)
                return View("Error");
            SimpleTaskDetailModel m = new SimpleTaskDetailModel();
            m.Logs = Util.getLogsForWebPage(Id);
            ViewBag.DisplayFormSourceAction = "getConfirmStuForm";
            ViewBag.DisplayFormSourceController = "TaskForm";
            return View("SimpleTaskDetail",m);
        }

        [HttpPost]
        public ActionResult ConfirmStuDetail(SimpleTaskDetailModel m, string bSubmit, Guid Id)
        {
            ValidateSession vs = new ValidateSession();
            switch (bSubmit)
            {
                case "Duyệt":
                    {
                        vs = Util.getValidateSession(m.Note, true, User.Identity.Name, Id);
                        ViewBag.NotifyResult = "Bạn đã duyệt thành công";
                        break;
                    }
                case "Từ chối":
                    {
                        vs = Util.getValidateSession(m.Note, false, User.Identity.Name, Id);
                        ViewBag.NotifyResult = "Bạn đã từ chối thành công";
                        break;
                    }
            }
            ValidateTaskHost h = new ValidateTaskHost();
            h.ApproveTask(Id, vs);
            return View("NotifyResult");
        }

        public ActionResult ExcemptTuition()
        {
            ViewBag.datasource = Url.Action("ExcemptTuitionData");
            return View("ManageTable");
        }

        public JsonResult ExcemptTuitionData()
        {
            var cs = Util.ValidateTaskListData(Request, x => x.Kind== 2 && x.Status == 2);
            cs.aaData.ForEach(
                x => Util.TableLinkMiscApprove(x, Url.Action("ExcemptTuitionDetail")));
            
            return Json(cs);
        }

        public ActionResult ExcemptTuitionDetail(Guid Id)
        {
            if (new wfdbEntities().TASKs.FirstOrDefault(x => x.Id == Id && x.Status == 2) == null)
                return View("Error");
            SimpleTaskDetailModel m = new SimpleTaskDetailModel();
            m.Logs = Util.getLogsForWebPage(Id);
            ViewBag.DisplayFormSourceAction = "getExcemptTuitionForm";
            ViewBag.DisplayFormSourceController = "TaskForm";
            return View("SimpleTaskDetail", m);
        }

        [HttpPost]
        public ActionResult ExcemptTuitionDetail(Guid Id, SimpleTaskDetailModel m, string bSubmit)
        {
            ValidateSession vs = new ValidateSession();
            switch (bSubmit)
            {
                case "Duyệt":
                    {
                        vs = Util.getValidateSession(m.Note, true, User.Identity.Name, Id);
                        ViewBag.NotifyResult = "Bạn đã duyệt thành công";
                        break;
                    }
                case "Từ chối":
                    {
                        vs = Util.getValidateSession(m.Note, false, User.Identity.Name, Id);
                        ViewBag.NotifyResult = "Bạn đã từ chối thành công";
                        break;
                    }
            }
            ValidateTaskHost h = new ValidateTaskHost();
            h.ApproveTask(Id, vs);
            return View("NotifyResult");
        }


        public ActionResult StudentCard()
        {
            ViewBag.datasource = Url.Action("StudentCardData");
            return View("ManageTable");
        }

        public JsonResult StudentCardData()
        {
            var cs = Util.ValidateTaskListData(Request, x => x.Kind == 3 && x.Status == 2);
            cs.aaData.ForEach(
                x => Util.TableLinkMiscApprove(x, Url.Action("StudentCardDetail")));
            
            return Json(cs);
        }

        public ActionResult StudentCardDetail(Guid Id)
        {
            if (new wfdbEntities().TASKs.FirstOrDefault(x => x.Id == Id && x.Status == 2) == null)
                return View("Error");
            SimpleTaskDetailModel m = new SimpleTaskDetailModel();
            m.Logs = Util.getLogsForWebPage(Id);
            ViewBag.DisplayFormSourceAction = "getStudentCardForm";
            ViewBag.DisplayFormSourceController = "TaskForm";
            return View("SimpleTaskDetail", m);
        }

        [HttpPost]
        public ActionResult StudentCardDetail(SimpleTaskDetailModel m, string bSubmit, Guid Id)
        {
            ValidateSession vs = new ValidateSession();
            switch (bSubmit)
            {
                case "Duyệt":
                    {
                        vs = Util.getValidateSession(m.Note, true, User.Identity.Name, Id);
                        ViewBag.NotifyResult = "Bạn đã duyệt thành công";
                        break;
                    }
                case "Từ chối":
                    {
                        vs = Util.getValidateSession(m.Note, false, User.Identity.Name, Id);
                        ViewBag.NotifyResult = "Bạn đã từ chối thành công";
                        break;
                    }
            }
            ValidateTaskHost h = new ValidateTaskHost();
            h.ApproveTask(Id, vs);
            return View("NotifyResult");
        }

        public ActionResult ReadyToPrintDoc()
        {
            ViewBag.Des = Url.Action("PrintDoc");
            ViewBag.datasource = Url.Action("ReadyToPrintDocData");
            return View();
        }

        [HttpPost]
        public ActionResult ReadyToPrintDoc(FormCollection f)
        {
            wfdbEntities db = new wfdbEntities();
            var cs = db.TASKs.Where(x => x.Status == 3);
            ValidateTaskHost h = new ValidateTaskHost();
            foreach(var item in cs)
            {
                h.MarkTaskDone(item.Id);
            }
            ViewBag.NotifyResult = "Bạn đã duyệt thành công";
            return View("NotifyResult");
        }

        public ActionResult PrintDoc()
        {
            List<Stream> lsStm = new List<Stream>();
            wfdbEntities db = new wfdbEntities();
            foreach (var t in db.TASKs.Where(x => x.Status == 3))
            {
                ReportClass f = new ReportClass();
                string studentNumCode = t.NumCode.ToString();
                var Student = db.STUDENTs.Where(x => x.NumCode == studentNumCode).SingleOrDefault();
                if (t.Kind == 1)
                {
                    f = new ConfirmStudentForm();
                    f.SetParameterValue("Name", Student.Name);
                    f.SetParameterValue("NumCode", Student.NumCode);
                    f.SetParameterValue("Birthday", Student.DoB);
                    f.SetParameterValue("Address", Student.Address);
                    f.SetParameterValue("Class", Student.Class);
                    f.SetParameterValue("StartYear", Student.StartYear);
                    f.SetParameterValue("TimeLast", Student.TIMELAST1.Description);
                    f.SetParameterValue("EduMode", Student.EDUMODE1.Description);
                    f.SetParameterValue("SYear", Util.getSYear(Student.StartYear.Value));
                    f.SetParameterValue("Reason", t.Reason.ToString());
                    f.SetParameterValue("Department", Student.CLASS1.DEPARTMENT1.Description);
                }
                else if (t.Kind == 2)
                {
                    f = new ExcemptTuitionForm();
                    f.SetParameterValue("Class", Student.Class);
                    f.SetParameterValue("Name", Student.Name);
                    f.SetParameterValue("NumCode", Student.NumCode);
                    f.SetParameterValue("Birthday", Student.DoB);
                    f.SetParameterValue("Department", Student.CLASS1.DEPARTMENT1.Description);
                    f.SetParameterValue("Hometown", t.HomeTown);
                    f.SetParameterValue("ParentName", t.ParentName);
                    f.SetParameterValue("Street", t.Street);
                    f.SetParameterValue("Ward", t.Ward);
                    f.SetParameterValue("District", t.District);
                    f.SetParameterValue("Province", t.Province);
                    f.SetParameterValue("Type", t.Type);
                    f.SetParameterValue("SYear", Util.getSYear(Student.StartYear.Value));
                    f.SetParameterValue("StartYear", Student.StartYear);
                    f.SetParameterValue("TimeLast", Student.TimeLast);
                    f.SetParameterValue("Tuition", t.Tuition);
                    f.SetParameterValue("Fault", t.Fault);
                }
                else if (t.Kind == 3)
                {
                    f = new StudentCardForm();
                    f.SetParameterValue("Name", Student.Name);
                    f.SetParameterValue("NumCode", Student.NumCode);
                    f.SetParameterValue("Birthday", Student.DoB);
                    f.SetParameterValue("EduMode", Student.EduMode);
                    f.SetParameterValue("SYear", Util.getSYear(Student.StartYear.Value));
                    f.SetParameterValue("Reason", t.Reason);
                    f.SetParameterValue("Department", Student.CLASS1.DEPARTMENT1.Description);
                }
                Stream stream = f.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
                lsStm.Add(stream);
                //PdfReader r = new PdfReader(stream);
            }
            Document document = null;
            PdfCopy writer = null;
            bool init = true;
            MemoryStream resultStm = new MemoryStream();
            foreach (var s in lsStm)
            {
                PdfReader reader = new PdfReader(s);
                int n = reader.NumberOfPages;
                if (init)
                {
                    init = false;
                    document = new Document(reader.GetPageSizeWithRotation(1));
                    writer = new PdfCopy(document, resultStm);
                    document.Open();
                }
                PdfImportedPage page;
                for (int i = 0; i < n; )
                {
                    ++i;
                    page = writer.GetImportedPage(reader, i);
                    writer.AddPage(page);
                }
                PRAcroForm form = reader.AcroForm;
                if (form != null)
                    writer.CopyAcroForm(reader);
            }
            writer.CloseStream = false;

            document.Close();
            
            resultStm.Position = 0;


            return File(resultStm, "application/pdf");   
        }

        //public ActionResult PrintDoc(Guid Id)
        //{
        //    ReportClass f = new ReportClass();
        //    wfdbEntities db = new wfdbEntities();
        //    var t = db.TASKs.Where(x => x.Id == Id).FirstOrDefault();
        //    string studentNumCode = t.NumCode.ToString();
        //    var Student = db.STUDENTs.Where(x => x.NumCode == studentNumCode).SingleOrDefault();
        //    if (t.Kind == 1)
        //    {
        //        f = new ConfirmStudentForm();
        //        f.SetParameterValue("Name", Student.Name);
        //        f.SetParameterValue("NumCode", Student.NumCode);
        //        f.SetParameterValue("Birthday", Student.DoB);
        //        f.SetParameterValue("Address", Student.Address);
        //        f.SetParameterValue("Class", Student.Class);
        //        f.SetParameterValue("StartYear", Student.StartYear);
        //        f.SetParameterValue("TimeLast", Student.TIMELAST1.Description);
        //        f.SetParameterValue("EduMode", Student.EDUMODE1.Description);
        //        f.SetParameterValue("SYear", Util.getSYear(Student.StartYear.Value));
        //        f.SetParameterValue("Reason", t.Reason.ToString());
        //        f.SetParameterValue("Department", Student.CLASS1.DEPARTMENT1.Description);
        //    }
        //    else if (t.Kind == 2)
        //    {
        //        f = new ExcemptTuitionForm();
        //        f.SetParameterValue("Class", Student.Class);
        //        f.SetParameterValue("Name", Student.Name);
        //        f.SetParameterValue("NumCode", Student.NumCode);
        //        f.SetParameterValue("Birthday", Student.DoB);
        //        f.SetParameterValue("Department", Student.CLASS1.DEPARTMENT1.Description);
        //        f.SetParameterValue("Hometown", t.HomeTown);
        //        f.SetParameterValue("ParentName", t.ParentName);
        //        f.SetParameterValue("Street", t.Street);
        //        f.SetParameterValue("Ward", t.Ward);
        //        f.SetParameterValue("District", t.District);
        //        f.SetParameterValue("Province", t.Province);
        //        f.SetParameterValue("Type", t.Type);
        //        f.SetParameterValue("SYear", Util.getSYear(Student.StartYear.Value));
        //        f.SetParameterValue("StartYear", Student.StartYear);
        //        f.SetParameterValue("TimeLast", Student.TimeLast);
        //        f.SetParameterValue("Tuition", t.Tuition);
        //        f.SetParameterValue("Fault", t.Fault);
        //    }
        //    else if (t.Kind == 3)
        //    {
        //        f = new StudentCardForm();
        //        f.SetParameterValue("Name", Student.Name);
        //        f.SetParameterValue("NumCode", Student.NumCode);
        //        f.SetParameterValue("Birthday", Student.DoB);
        //        f.SetParameterValue("EduMode", Student.EduMode);
        //        f.SetParameterValue("SYear", Util.getSYear(Student.StartYear.Value));
        //        f.SetParameterValue("Reason", t.Reason);
        //        f.SetParameterValue("Department", Student.CLASS1.DEPARTMENT1.Description);
        //    }
        //    Stream stream = f.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);

        //    return File(stream, "application/pdf");
        //}

        public JsonResult ReadyToPrintDocData()
        {
            var cs = Util.ValidateTaskListData(Request,x => x.Status == 3);
            cs.aaData.ForEach(
                x => x[5] = "<input type='hidden' value='" + x[5] + "'/>"+
                    Util.getsTableLink(new { @class = Util.detail }, new { title = "Xem", href = Url.Action("getForm", new { id = x[5] }) })
                );
            
            return Json(cs);
        }

        public ActionResult getForm(Guid id)
        {
            wfdbEntities db = new wfdbEntities();
            var t =db.TASKs.Where(x => x.Id == id).FirstOrDefault();
            if (t == null)
                return View("Error");
            byte taskkind = t.Kind.Value;
            if (taskkind == 2)
            {
                Util.getExcemptStudentForm(this.HttpContext, id);
            }
            else if (taskkind == 1)
            {
                Util.getConfirmStuForm(this.HttpContext, id);
            }
            else if (taskkind == 3)
            {
                Util.getStudentCardForm(this.HttpContext, id);
            }
            return RedirectToAction("DocForm.aspx", "AspNetForms");
        }

        //public ActionResult MarkDone(Guid Id)
        //{
        //    ValidateTaskHost h = new ValidateTaskHost();
        //    h.MarkDone(Id);
        //    ViewBag.NotifyResult = "Đánh dấu hoàn thành thành công";
        //    return View("NotifyResult");
        //}
    }
}
